package com.warningrc.module.user.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.warningrc.module.user.po.User;
import com.warningrc.module.user.vo.UserVo;
import com.warningrc.system.data.dao.GenericDao;

public class UserServiceImpl implements UserService {
	private GenericDao<User> genericDao;

	public GenericDao<User> getGenericDao() {
		return genericDao;
	}

	public void setGenericDao(GenericDao<User> genericDao) {
		this.genericDao = genericDao;
	}

	@Override
	public void deleteUser(String userId) {
		genericDao.delete(new User(userId));
	}

	@Override
	public UserVo getUser(String userId) {
		User user = genericDao.read((Serializable) userId);
		if (user == null)
			return null;
		UserVo userVo = new UserVo();
		BeanUtils.copyProperties(user, userVo);
		return userVo;
	}

	@Override
	public Serializable saveUser(UserVo userVo) {
		User user = new User();
		BeanUtils.copyProperties(userVo, user);
		return genericDao.create(user);
	}

	@Override
	public void updateUser(UserVo userVo) {
		User user = new User();
		BeanUtils.copyProperties(userVo, user);
		genericDao.update(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserVo> getAll() {
		List users = genericDao.readAll();
		for (int i = 0; i < users.size(); i++) {
			User user = (User) users.get(i);
			Object userVo = new UserVo();
			BeanUtils.copyProperties(user, userVo);
			users.set(i, userVo);
		}
		return (List<UserVo>) users;
	}

	@Override
	public String login(String username, String password) {
		String hql = "from User user where user.userName=:userName";
		List<User> users = genericDao.read(hql, "userName", username);
		if (users != null && users.size() > 1) {
			User user = users.get(0);
			if (user.getUserPassword().equals(password))
				return user.getUserId();
		}
		return null;
	}
}
